package com.lz.ub

import android.content.Context
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import androidx.annotation.MainThread
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.felhr.usbserial.UsbSerialDevice

object UBCConfig {

    //重启的时间
    const val RESTART_TIME = 2000L

    //插入设备
    const val DEVICE_ATTACHED = 0

    //拔出设备
    const val DEVICE_DETACHED = 1

    //设备权限允许
    const val DEVICE_PERMISSION_GRANTED = 0

    //设备权限被拒绝
    const val DEVICE_PERMISSION_REFUSE = 1

    //辅助模式
    var isAssistModel = false
        private set

    //设备插拔监听
    private val observers = ArrayList<UsbStateObserver>()

    //设备的一些权限提示
    private val callbacks = ArrayList<UsbStateCallback>()

    //是否支持
    fun isSupport(device: UsbDevice): Boolean = UsbSerialDevice.isSupported(device)

    fun init(
        isAssistModel: Boolean, context: Context, baudRate: Int = UBC_BAUD_RATE,
        dataB: Int = UBC_DATA_BITS, stopB: Int = UBC_STOP_BITS, parity: Int = UBC_PARITY
    ) {
        this.isAssistModel = isAssistModel
        val usbManager = context.getSystemService(Context.USB_SERVICE) as UsbManager
        UBCManager.init(usbManager, baudRate, dataB, stopB, parity)
        UBCAssistManager.init(usbManager, baudRate, dataB, stopB, parity)
    }

    fun switchModel(isAssistModel: Boolean) {
        if (this.isAssistModel == isAssistModel) return
        this.isAssistModel = isAssistModel
        if (isAssistModel) {
            UBCAssistManager.get().close()
        } else {
            UBCManager.get().close()
        }
    }

    internal fun deviceEmpty() {
        callbacks.forEach { it.onEmpty() }
    }

    internal fun devicePermission(device: UsbDevice, state: Int) {
        callbacks.forEach { it.onPermission(device, state) }
    }

    internal fun deviceState(device: UsbDevice, state: Int) {
        observers.forEach { it.onStateChanged(device, state) }
    }

    //插入USB设备
    internal fun addUsbDevice(device: UsbDevice) {
        if (isAssistModel) {
            UBCAssistManager.get().addUsbDevice(device)
        } else {
            UBCManager.get().addUsbDevice(device)
        }
    }

    //拔出USB设备
    internal fun removeUsbDevice(device: UsbDevice) {
        if (isAssistModel) {
            UBCAssistManager.get().removeUsbDevice(device)
        } else {
            UBCManager.get().removeUsbDevice(device)
        }
    }

    @MainThread
    fun observe(owner: LifecycleOwner, observer: UsbStateObserver) {
        if (owner.lifecycle.currentState == Lifecycle.State.DESTROYED) return
        observers.add(observer)
        owner.lifecycle.addObserver(object : LifecycleEventObserver {
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                if (event == Lifecycle.Event.ON_DESTROY) {
                    removeObserver(observer)
                }
            }
        })
    }

    /**
     * 注意当适当使用 @see [removeObserver]
     */
    @MainThread
    fun observeForever(observer: UsbStateObserver) {
        observers.add(observer)
    }

    @MainThread
    fun removeObserver(observer: UsbStateObserver) {
        observers.remove(observer)
    }

    fun addUsbStateCallback(callback: UsbStateCallback) {
        callbacks.add(callback)
    }

    fun removeUsbStateCallback(callback: UsbStateCallback) {
        callbacks.remove(callback)
    }

    interface UsbStateObserver {

        /**
         * usb状态改变,
         * @param state [DEVICE_ATTACHED], [DEVICE_DETACHED]
         */
        fun onStateChanged(usbDevice: UsbDevice, state: Int)
    }

    interface UsbStateCallback {

        /**
         * @param state [DEVICE_PERMISSION_GRANTED], [DEVICE_PERMISSION_REFUSE]
         */
        fun onPermission(usbDevice: UsbDevice, state: Int)

        fun onEmpty()
    }
}